let app = window.go?.main?.App
const runtime = window.runtime

const checkApp = () => {
  if (!app) throw new Error('App not initialized')
}

export const templateAPI = {
  async create(name, content) {
    checkApp()
    return await app.CreateTemplate(name, content)
  },
  async createDocx(name, base64Data) {
    checkApp()
    return JSON.parse(await app.CreateDocxTemplate(name, base64Data))
  },
  async get(id) {
    checkApp()
    return await app.GetTemplate(id)
  },
  async list() {
    checkApp()
    return JSON.parse(await app.ListTemplates())
  },
  async update(id, name, content) {
    checkApp()
    return await app.UpdateTemplate(id, name, content)
  },
  async delete(id) {
    checkApp()
    return await app.DeleteTemplate(id)
  },
  async selectFolder() {
    checkApp()
    return await app.SelectTemplatesFolder()
  },
  async importFromFolder(folderPath) {
    checkApp()
    return JSON.parse(await app.ImportTemplatesFromFolder(folderPath))
  },
  async getDefaultFolder() {
    checkApp()
    return await app.GetDefaultTemplatesFolder()
  },
}

export const ocrAPI = {
  async recognize(imagePath) {
    checkApp()
    return JSON.parse(await app.RecognizeImage(imagePath))
  },
  async setConfig(url, key, secret) {
    checkApp()
    return await app.SetOCRConfig(url, key, secret)
  },
  async setSiliconFlowAPIKey(apiKey) {
    checkApp()
    return await app.SetSiliconFlowAPIKey(apiKey)
  },
  async getSiliconFlowModels() {
    checkApp()
    return JSON.parse(await app.GetSiliconFlowModels())
  },
  async recognizeWithSiliconFlowStream(modelID, imageBase64, onChunk) {
    checkApp()
    if (!runtime) throw new Error('Wails runtime not available')
    
    return new Promise((resolve, reject) => {
      const { EventsOn, EventsOff } = runtime
      const cleanup = () => {
        EventsOff('ocr-stream-chunk', chunkHandler)
        EventsOff('ocr-stream-done', doneHandler)
        EventsOff('ocr-stream-error', errorHandler)
      }
      
      const chunkHandler = (chunk) => onChunk?.(chunk)
      const doneHandler = () => { cleanup(); resolve() }
      const errorHandler = (error) => { cleanup(); reject(new Error(error)) }
      
      EventsOn('ocr-stream-chunk', chunkHandler)
      EventsOn('ocr-stream-done', doneHandler)
      EventsOn('ocr-stream-error', errorHandler)
      
      try {
        app.RecognizeImageWithSiliconFlowStream(modelID, imageBase64)
      } catch (err) {
        cleanup()
        reject(err)
      }
    })
  },
}

export const configAPI = {
  async get() {
    checkApp()
    return JSON.parse(await app.GetAppConfig())
  },
  async save(config) {
    checkApp()
    return await app.SaveAppConfig(JSON.stringify(config))
  },
}

export const fieldMappingAPI = {
  async get(templateID) {
    checkApp()
    return JSON.parse(await app.GetFieldMapping(templateID))
  },
  async save(mapping) {
    checkApp()
    return await app.SaveFieldMapping(JSON.stringify(mapping))
  },
  async apply(templateID, ocrData) {
    checkApp()
    return JSON.parse(await app.ApplyFieldMapping(templateID, JSON.stringify(ocrData)))
  },
}

export const fileAPI = {
  async fillAndSave(templateID, data, filename) {
    checkApp()
    return await app.FillAndSaveTemplate(templateID, JSON.stringify(data), filename)
  },
  async saveImageFile(filename, base64Data) {
    checkApp()
    return await app.SaveImageFile(filename, base64Data)
  },
  async openFile(filePath) {
    checkApp()
    return await app.OpenFile(filePath)
  },
}

export const batchOCRAPI = {
  async selectMaterialsFolder() {
    checkApp()
    return await app.SelectMaterialsFolder()
  },
  async recognizeFolder(folderPath, modelID, onProgress) {
    checkApp()
    if (!runtime) throw new Error('Wails runtime not available')
    
    return new Promise((resolve, reject) => {
      const { EventsOn, EventsOff } = runtime
      let progressHandler = null
      
      const cleanup = () => {
        if (progressHandler) {
          EventsOff('batch-ocr-progress', progressHandler)
        }
      }
      
      // 设置进度监听（可选）
      if (onProgress && typeof onProgress === 'function') {
        progressHandler = (progressJSON) => {
          try {
            const progress = JSON.parse(progressJSON)
            onProgress(progress)
          } catch (e) {
            console.error('解析进度失败:', e)
          }
        }
        EventsOn('batch-ocr-progress', progressHandler)
      }
      
      try {
        app.RecognizeFolder(folderPath, modelID).then((result) => {
          cleanup()
          resolve(JSON.parse(result))
        }).catch((err) => {
          cleanup()
          reject(err)
        })
      } catch (err) {
        cleanup()
        reject(err)
      }
    })
  },
  async extractFieldsFromOCR(templateID, ocrData, ocrText) {
    checkApp()
    return JSON.parse(await app.ExtractFieldsFromOCR(templateID, JSON.stringify(ocrData), ocrText))
  },
}